import { useEffect, useState } from "react";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";
import { Flex, message, Upload } from "antd";
import type { UploadProps } from "antd";
import type { FileType } from "./types/index.type";

const getBase64 = (img: FileType, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result as string));
  reader.readAsDataURL(img);
};

const UploadCard = ({ onSuccess, imgUrl }: { onSuccess: (file: FileType) => void; imgUrl?: string }) => {
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();

  const handleChange: UploadProps["onChange"] = async ({ file }) => {
    const isLt10M = file.size! / 1024 / 1024 < 10;
    if (!isLt10M) {
      message.error("Image must smaller than 10MB!");
    }
    if (file.status === "uploading") {
      setLoading(true);
      return;
    }
    getBase64(file as FileType, url => {
      setImageUrl(url);
      onSuccess(file as FileType);
      setLoading(false);
    });
  };

  const uploadButton = (
    <button style={{ border: 0, background: "none" }} type="button">
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>上传</div>
    </button>
  );

  useEffect(() => {
    imgUrl && setImageUrl(imgUrl);
  }, [imgUrl]);
  return (
    <Flex gap="middle" wrap>
      <Upload
        name="UploadCard"
        listType="picture-card"
        accept="image/*"
        showUploadList={false}
        beforeUpload={() => false}
        onChange={handleChange}
        customRequest={() => {}}
      >
        {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: "100%" }} /> : uploadButton}
      </Upload>
    </Flex>
  );
};

export default UploadCard;
